package cn.venny.qiniu.config;

import cn.venny.qiniu.annotation.EnableQiNiu;
import cn.venny.qiniu.properties.QiNiuProperties;
import cn.venny.qiniu.service.QiNiuUploadService;
import cn.venny.qiniu.service.impl.DefaultQiNiuUploadServiceImpl;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;

/**
 * @author : Vick C
 * @version : v1.0
 * 2020/6/19
 */
@ComponentScan("cn.venny.qiniu")
@org.springframework.context.annotation.Configuration
@ConditionalOnBean(annotation = EnableQiNiu.class)
@EnableConfigurationProperties(QiNiuProperties.class)
public class QiNiuAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean(Region.class)
    public Region getRegion() {
        return Region.autoRegion();
    }

    @Bean
    @ConditionalOnMissingBean(Configuration.class)
    public Configuration getConfiguration(Region region) {
        return new Configuration(region);
    }

    @Bean
    @ConditionalOnMissingBean(UploadManager.class)
    public UploadManager getUploadManager(Configuration configuration) {
        return new UploadManager(configuration);
    }

    @Bean
    @ConditionalOnMissingBean(Auth.class)
    public Auth getAuth(QiNiuProperties properties) {
        return Auth.create(properties.getAccessKey(), properties.getAccessKeySecret());
    }

    @Bean
    @ConditionalOnMissingBean(BucketManager.class)
    public BucketManager getBucketManager(QiNiuProperties properties, Configuration configuration) {
        return new BucketManager(getAuth(properties), configuration);
    }

    @Bean
    @ConditionalOnMissingBean(QiNiuUploadService.class)
    public QiNiuUploadService qiNiuUploadService(Auth auth, QiNiuProperties properties, UploadManager uploadManager, BucketManager bucketManager) {
        return new DefaultQiNiuUploadServiceImpl(auth, properties, uploadManager, bucketManager);
    }
}
